docu cleanup; marked contenthandler stuff as @since 1.WD
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class for viewing MediaWiki article and history.
9 *
10 * This maintains WikiPage functions for backwards compatibility.
11 *
12 * @TODO: move and rewrite code to an Action class
13 *
14 * See design.txt for an overview.
15 * Note: edit user interface and cache support functions have been
16 * moved to separate EditPage and HTMLFileCache classes.
17 *
18 * @internal documentation reviewed 15 Mar 2010
19 */
20 class Article extends Page {
21 /**@{{
22 * @private
23 */
24
25 /**
26 * @var IContextSource
27 */
28 protected $mContext;
29
30 /**
31 * @var WikiPage
32 */
33 protected $mPage;
34
35 /**
36 * @var ParserOptions: ParserOptions object for $wgUser articles
37 */
38 public $mParserOptions;
39
40 var $mContent; // !< #BC cruft
41
42 /**
43 * @var Content
44 * @since 1.WD
45 */
46 var $mContentObject;
47
48 var $mContentLoaded = false; // !<
49 var $mOldId; // !<
50
51 /**
52 * @var Title
53 */
54 var $mRedirectedFrom = null;
55
56 /**
57 * @var mixed: boolean false or URL string
58 */
59 var $mRedirectUrl = false; // !<
60 var $mRevIdFetched = 0; // !<
61
62 /**
63 * @var Revision
64 */
65 var $mRevision = null;
66
67 /**
68 * @var ParserOutput
69 */
70 var $mParserOutput;
71
72 /**@}}*/
73
74 /**
75 * Constructor and clear the article
76 * @param $title Title Reference to a Title object.
77 * @param $oldId Integer revision ID, null to fetch from request, zero for current
78 */
79 public function __construct( Title $title, $oldId = null ) {
80 $this->mOldId = $oldId;
81 $this->mPage = $this->newPage( $title );
82 }
83
84 /**
85 * @param $title Title
86 * @return WikiPage
87 */
88 protected function newPage( Title $title ) {
89 return new WikiPage( $title );
90 }
91
92 /**
93 * Constructor from a page id
94 * @param $id Int article ID to load
95 * @return Article|null
96 */
97 public static function newFromID( $id ) {
98 $t = Title::newFromID( $id );
99 # @todo FIXME: Doesn't inherit right
100 return $t == null ? null : new self( $t );
101 # return $t == null ? null : new static( $t ); // PHP 5.3
102 }
103
104 /**
105 * Create an Article object of the appropriate class for the given page.
106 *
107 * @param $title Title
108 * @param $context IContextSource
109 * @return Article object
110 */
111 public static function newFromTitle( $title, IContextSource $context ) {
112 if ( NS_MEDIA == $title->getNamespace() ) {
113 // FIXME: where should this go?
114 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
115 }
116
117 $page = null;
118 wfRunHooks( 'ArticleFromTitle', array( &$title, &$page ) );
119 if ( !$page ) {
120 switch( $title->getNamespace() ) {
121 case NS_FILE:
122 $page = new ImagePage( $title ); #FIXME: teach ImagePage to use ContentHandler
123 break;
124 case NS_CATEGORY:
125 $page = new CategoryPage( $title ); #FIXME: teach ImagePage to use ContentHandler
126 break;
127 default:
128 $handler = ContentHandler::getForTitle( $title );
129 $page = $handler->createArticle( $title );
130 }
131 }
132 $page->setContext( $context );
133
134 return $page;
135 }
136
137 /**
138 * Create an Article object of the appropriate class for the given page.
139 *
140 * @param $page WikiPage
141 * @param $context IContextSource
142 * @return Article object
143 */
144 public static function newFromWikiPage( WikiPage $page, IContextSource $context ) {
145 $article = self::newFromTitle( $page->getTitle(), $context );
146 $article->mPage = $page; // override to keep process cached vars
147 return $article;
148 }
149
150 /**
151 * Tell the page view functions that this view was redirected
152 * from another page on the wiki.
153 * @param $from Title object.
154 */
155 public function setRedirectedFrom( Title $from ) {
156 $this->mRedirectedFrom = $from;
157 }
158
159 /**
160 * Get the title object of the article
161 *
162 * @return Title object of this page
163 */
164 public function getTitle() {
165 return $this->mPage->getTitle();
166 }
167
168 /**
169 * Get the WikiPage object of this instance
170 *
171 * @since 1.19
172 * @return WikiPage
173 */
174 public function getPage() {
175 return $this->mPage;
176 }
177
178 /**
179 * Clear the object
180 */
181 public function clear() {
182 $this->mContentLoaded = false;
183
184 $this->mRedirectedFrom = null; # Title object if set
185 $this->mRevIdFetched = 0;
186 $this->mRedirectUrl = false;
187
188 $this->mPage->clear();
189 }
190
191 /**
192 * Note that getContent/loadContent do not follow redirects anymore.
193 * If you need to fetch redirectable content easily, try
194 * the shortcut in WikiPage::getRedirectTarget()
195 *
196 * This function has side effects! Do not use this function if you
197 * only want the real revision text if any.
198 *
199 * @deprecated in 1.WD; use getContentObject() instead
200 *
201 * @return string The text of this revision
202 */
203 public function getContent() {
204 wfDeprecated( __METHOD__, '1.WD' );
205 $content = $this->getContentObject();
206 return ContentHandler::getContentText( $content );
207 }
208
209 /**
210 * Returns a Content object representing the pages effective display content,
211 * not necessarily the revision's content!
212 *
213 * Note that getContent/loadContent do not follow redirects anymore.
214 * If you need to fetch redirectable content easily, try
215 * the shortcut in WikiPage::getRedirectTarget()
216 *
217 * This function has side effects! Do not use this function if you
218 * only want the real revision text if any.
219 *
220 * @return Content
221 *
222 * @since 1.WD
223 */
224 protected function getContentObject() {
225 global $wgUser;
226
227 wfProfileIn( __METHOD__ );
228
229 if ( $this->mPage->getID() === 0 ) {
230 # If this is a MediaWiki:x message, then load the messages
231 # and return the message value for x.
232 if ( $this->getTitle()->getNamespace() == NS_MEDIAWIKI ) {
233 $text = $this->getTitle()->getDefaultMessageText();
234 if ( $text === false ) {
235 $text = '';
236 }
237
238 $content = ContentHandler::makeContent( $text, $this->getTitle() );
239 } else {
240 $content = new MessageContent( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', null, 'parsemag' );
241 }
242 wfProfileOut( __METHOD__ );
243
244 return $content;
245 } else {
246 $this->fetchContentObject();
247 wfProfileOut( __METHOD__ );
248
249 return $this->mContentObject;
250 }
251 }
252
253 /**
254 * @return int The oldid of the article that is to be shown, 0 for the
255 * current revision
256 */
257 public function getOldID() {
258 if ( is_null( $this->mOldId ) ) {
259 $this->mOldId = $this->getOldIDFromRequest();
260 }
261
262 return $this->mOldId;
263 }
264
265 /**
266 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
267 *
268 * @return int The old id for the request
269 */
270 public function getOldIDFromRequest() {
271 global $wgRequest;
272
273 $this->mRedirectUrl = false;
274
275 $oldid = $wgRequest->getIntOrNull( 'oldid' );
276
277 if ( $oldid === null ) {
278 return 0;
279 }
280
281 if ( $oldid !== 0 ) {
282 # Load the given revision and check whether the page is another one.
283 # In that case, update this instance to reflect the change.
284 if ( $oldid === $this->mPage->getLatest() ) {
285 $this->mRevision = $this->mPage->getRevision();
286 } else {
287 $this->mRevision = Revision::newFromId( $oldid );
288 if ( $this->mRevision !== null ) {
289 // Revision title doesn't match the page title given?
290 if ( $this->mPage->getID() != $this->mRevision->getPage() ) {
291 $function = array( get_class( $this->mPage ), 'newFromID' );
292 $this->mPage = call_user_func( $function, $this->mRevision->getPage() );
293 }
294 }
295 }
296 }
297
298 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
299 $nextid = $this->getTitle()->getNextRevisionID( $oldid );
300 if ( $nextid ) {
301 $oldid = $nextid;
302 $this->mRevision = null;
303 } else {
304 $this->mRedirectUrl = $this->getTitle()->getFullURL( 'redirect=no' );
305 }
306 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
307 $previd = $this->getTitle()->getPreviousRevisionID( $oldid );
308 if ( $previd ) {
309 $oldid = $previd;
310 $this->mRevision = null;
311 }
312 }
313
314 return $oldid;
315 }
316
317 /**
318 * Load the revision (including text) into this object
319 *
320 * @deprecated in 1.19; use fetchContent()
321 */
322 function loadContent() {
323 wfDeprecated( __METHOD__, '1.19' );
324 $this->fetchContent();
325 }
326
327 /**
328 * Get text of an article from database
329 * Does *NOT* follow redirects.
330 *
331 * @return mixed string containing article contents, or false if null
332 * @deprecated in 1.WD, use getContentObject() instead
333 */
334 protected function fetchContent() { #BC cruft!
335 wfDeprecated( __METHOD__, '1.WD' );
336
337 if ( $this->mContentLoaded && $this->mContent ) {
338 return $this->mContent;
339 }
340
341 wfProfileIn( __METHOD__ );
342
343 $content = $this->fetchContentObject();
344
345 $this->mContent = ContentHandler::getContentText( $content ); #FIXME: get rid of mContent everywhere!
346 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ); #BC cruft!
347
348 wfProfileOut( __METHOD__ );
349
350 return $this->mContent;
351 }
352
353
354 /**
355 * Get text content object
356 * Does *NOT* follow redirects.
357 * TODO: when is this null?
358 *
359 * @return Content|null
360 *
361 * @since 1.WD
362 */
363 protected function fetchContentObject() {
364 if ( $this->mContentLoaded ) {
365 return $this->mContentObject;
366 }
367
368 wfProfileIn( __METHOD__ );
369
370 $this->mContentLoaded = true;
371 $this->mContent = null;
372
373 $oldid = $this->getOldID();
374
375 # Pre-fill content with error message so that if something
376 # fails we'll have something telling us what we intended.
377 $t = $this->getTitle()->getPrefixedText();
378 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
379 $this->mContentObject = new MessageContent( 'missing-article', array($t, $d), array() ) ; // @todo: this isn't page content but a UI message. horrible.
380
381 if ( $oldid ) {
382 # $this->mRevision might already be fetched by getOldIDFromRequest()
383 if ( !$this->mRevision ) {
384 $this->mRevision = Revision::newFromId( $oldid );
385 if ( !$this->mRevision ) {
386 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
387 wfProfileOut( __METHOD__ );
388 return false;
389 }
390 }
391 } else {
392 if ( !$this->mPage->getLatest() ) {
393 wfDebug( __METHOD__ . " failed to find page data for title " . $this->getTitle()->getPrefixedText() . "\n" );
394 wfProfileOut( __METHOD__ );
395 return false;
396 }
397
398 $this->mRevision = $this->mPage->getRevision();
399
400 if ( !$this->mRevision ) {
401 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id " . $this->mPage->getLatest() . "\n" );
402 wfProfileOut( __METHOD__ );
403 return false;
404 }
405 }
406
407 // @todo FIXME: Horrible, horrible! This content-loading interface just plain sucks.
408 // We should instead work with the Revision object when we need it...
409 $this->mContentObject = $this->mRevision->getContent( Revision::FOR_THIS_USER ); // Loads if user is allowed
410 $this->mRevIdFetched = $this->mRevision->getId();
411
412 wfRunHooks( 'ArticleAfterFetchContentObject', array( &$this, &$this->mContentObject ) ); #FIXME: register new hook
413
414 wfProfileOut( __METHOD__ );
415
416 return $this->mContentObject;
417 }
418
419 /**
420 * No-op
421 * @deprecated since 1.18
422 */
423 public function forUpdate() {
424 wfDeprecated( __METHOD__, '1.18' );
425 }
426
427 /**
428 * Returns true if the currently-referenced revision is the current edit
429 * to this page (and it exists).
430 * @return bool
431 */
432 public function isCurrent() {
433 # If no oldid, this is the current version.
434 if ( $this->getOldID() == 0 ) {
435 return true;
436 }
437
438 return $this->mPage->exists() && $this->mRevision && $this->mRevision->isCurrent();
439 }
440
441 /**
442 * Get the fetched Revision object depending on request parameters or null
443 * on failure.
444 *
445 * @since 1.19
446 * @return Revision|null
447 */
448 public function getRevisionFetched() {
449 $this->fetchContentObject();
450
451 return $this->mRevision;
452 }
453
454 /**
455 * Use this to fetch the rev ID used on page views
456 *
457 * @return int revision ID of last article revision
458 */
459 public function getRevIdFetched() {
460 if ( $this->mRevIdFetched ) {
461 return $this->mRevIdFetched;
462 } else {
463 return $this->mPage->getLatest();
464 }
465 }
466
467 /**
468 * This is the default action of the index.php entry point: just view the
469 * page of the given title.
470 */
471 public function view() {
472 global $wgUser, $wgOut, $wgRequest, $wgParser;
473 global $wgUseFileCache, $wgUseETag, $wgDebugToolbar;
474
475 wfProfileIn( __METHOD__ );
476
477 # Get variables from query string
478 # As side effect this will load the revision and update the title
479 # in a revision ID is passed in the request, so this should remain
480 # the first call of this method even if $oldid is used way below.
481 $oldid = $this->getOldID();
482
483 # Another whitelist check in case getOldID() is altering the title
484 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'read', $wgUser );
485 if ( count( $permErrors ) ) {
486 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
487 wfProfileOut( __METHOD__ );
488 throw new PermissionsError( 'read', $permErrors );
489 }
490
491 # getOldID() may as well want us to redirect somewhere else
492 if ( $this->mRedirectUrl ) {
493 $wgOut->redirect( $this->mRedirectUrl );
494 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
495 wfProfileOut( __METHOD__ );
496
497 return;
498 }
499
500 # If we got diff in the query, we want to see a diff page instead of the article.
501 if ( $wgRequest->getCheck( 'diff' ) ) {
502 wfDebug( __METHOD__ . ": showing diff page\n" );
503 $this->showDiffPage();
504 wfProfileOut( __METHOD__ );
505
506 return;
507 }
508
509 # Set page title (may be overridden by DISPLAYTITLE)
510 $wgOut->setPageTitle( $this->getTitle()->getPrefixedText() );
511
512 $wgOut->setArticleFlag( true );
513 # Allow frames by default
514 $wgOut->allowClickjacking();
515
516 $parserCache = ParserCache::singleton();
517
518 $parserOptions = $this->getParserOptions();
519 # Render printable version, use printable version cache
520 if ( $wgOut->isPrintable() ) {
521 $parserOptions->setIsPrintable( true );
522 $parserOptions->setEditSection( false );
523 } elseif ( !$this->isCurrent() || !$this->getTitle()->quickUserCan( 'edit' ) ) {
524 $parserOptions->setEditSection( false );
525 }
526
527 # Try client and file cache
528 if ( !$wgDebugToolbar && $oldid === 0 && $this->mPage->checkTouched() ) {
529 if ( $wgUseETag ) {
530 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
531 }
532
533 # Is it client cached?
534 if ( $wgOut->checkLastModified( $this->mPage->getTouched() ) ) {
535 wfDebug( __METHOD__ . ": done 304\n" );
536 wfProfileOut( __METHOD__ );
537
538 return;
539 # Try file cache
540 } elseif ( $wgUseFileCache && $this->tryFileCache() ) {
541 wfDebug( __METHOD__ . ": done file cache\n" );
542 # tell wgOut that output is taken care of
543 $wgOut->disable();
544 $this->mPage->doViewUpdates( $wgUser );
545 wfProfileOut( __METHOD__ );
546
547 return;
548 }
549 }
550
551 # Should the parser cache be used?
552 $useParserCache = $this->mPage->isParserCacheUsed( $parserOptions, $oldid );
553 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
554 if ( $wgUser->getStubThreshold() ) {
555 wfIncrStats( 'pcache_miss_stub' );
556 }
557
558 $this->showRedirectedFromHeader();
559 $this->showNamespaceHeader();
560
561 # Iterate through the possible ways of constructing the output text.
562 # Keep going until $outputDone is set, or we run out of things to do.
563 $pass = 0;
564 $outputDone = false;
565 $this->mParserOutput = false;
566
567 while ( !$outputDone && ++$pass ) {
568 switch( $pass ) {
569 case 1:
570 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
571 break;
572 case 2:
573 # Early abort if the page doesn't exist
574 if ( !$this->mPage->exists() ) {
575 wfDebug( __METHOD__ . ": showing missing article\n" );
576 $this->showMissingArticle();
577 wfProfileOut( __METHOD__ );
578 return;
579 }
580
581 # Try the parser cache
582 if ( $useParserCache ) {
583 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
584
585 if ( $this->mParserOutput !== false ) {
586 if ( $oldid ) {
587 wfDebug( __METHOD__ . ": showing parser cache contents for current rev permalink\n" );
588 $this->setOldSubtitle( $oldid );
589 } else {
590 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
591 }
592 $wgOut->addParserOutput( $this->mParserOutput );
593 # Ensure that UI elements requiring revision ID have
594 # the correct version information.
595 $wgOut->setRevisionId( $this->mPage->getLatest() );
596 # Preload timestamp to avoid a DB hit
597 $cachedTimestamp = $this->mParserOutput->getTimestamp();
598 if ( $cachedTimestamp !== null ) {
599 $wgOut->setRevisionTimestamp( $cachedTimestamp );
600 $this->mPage->setTimestamp( $cachedTimestamp );
601 }
602 $outputDone = true;
603 }
604 }
605 break;
606 case 3:
607 # This will set $this->mRevision if needed
608 $this->fetchContentObject();
609
610 # Are we looking at an old revision
611 if ( $oldid && $this->mRevision ) {
612 $this->setOldSubtitle( $oldid );
613
614 if ( !$this->showDeletedRevisionHeader() ) {
615 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
616 wfProfileOut( __METHOD__ );
617 return;
618 }
619 }
620
621 # Ensure that UI elements requiring revision ID have
622 # the correct version information.
623 $wgOut->setRevisionId( $this->getRevIdFetched() );
624 # Preload timestamp to avoid a DB hit
625 $wgOut->setRevisionTimestamp( $this->getTimestamp() );
626
627 # Pages containing custom CSS or JavaScript get special treatment
628 if ( $this->getTitle()->isCssOrJsPage() || $this->getTitle()->isCssJsSubpage() ) {
629 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
630 $this->showCssOrJsPage();
631 $outputDone = true;
632 } elseif( !wfRunHooks( 'ArticleContentViewCustom', array( $this->fetchContentObject(), $this->getTitle(), $wgOut ) ) ) { #FIXME: document new hook!
633 # Allow extensions do their own custom view for certain pages
634 $outputDone = true;
635 } elseif( Hooks::isRegistered( 'ArticleViewCustom' ) && !wfRunHooks( 'ArticleViewCustom', array( $this->fetchContent(), $this->getTitle(), $wgOut ) ) ) { #FIXME: fetchContent() is deprecated! #FIXME: deprecate hook!
636 # Allow extensions do their own custom view for certain pages
637 $outputDone = true;
638 } else {
639 $content = $this->getContentObject();
640 $rt = $content->getRedirectChain();
641 if ( $rt ) {
642 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
643 # Viewing a redirect page (e.g. with parameter redirect=no)
644 $wgOut->addHTML( $this->viewRedirect( $rt ) );
645 # Parse just to get categories, displaytitle, etc.
646 $this->mParserOutput = $content->getParserOutput( $this->getContext(), $oldid, $parserOptions, false );
647 $wgOut->addParserOutputNoText( $this->mParserOutput );
648 $outputDone = true;
649 }
650 }
651 break;
652 case 4:
653 # Run the parse, protected by a pool counter
654 wfDebug( __METHOD__ . ": doing uncached parse\n" );
655
656 // @todo: shouldn't we be passing $this->getPage() to PoolWorkArticleView instead of plain $this?
657 $poolArticleView = new PoolWorkArticleView( $this, $parserOptions,
658 $this->getRevIdFetched(), $useParserCache, $this->getContentObject(), $this->getContext() );
659
660 if ( !$poolArticleView->execute() ) {
661 $error = $poolArticleView->getError();
662 if ( $error ) {
663 $wgOut->clearHTML(); // for release() errors
664 $wgOut->enableClientCache( false );
665 $wgOut->setRobotPolicy( 'noindex,nofollow' );
666
667 $errortext = $error->getWikiText( false, 'view-pool-error' );
668 $wgOut->addWikiText( '<div class="errorbox">' . $errortext . '</div>' );
669 }
670 # Connection or timeout error
671 wfProfileOut( __METHOD__ );
672 return;
673 }
674
675 $this->mParserOutput = $poolArticleView->getParserOutput();
676 $wgOut->addParserOutput( $this->mParserOutput );
677
678 # Don't cache a dirty ParserOutput object
679 if ( $poolArticleView->getIsDirty() ) {
680 $wgOut->setSquidMaxage( 0 );
681 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
682 }
683
684 $outputDone = true;
685 break;
686 # Should be unreachable, but just in case...
687 default:
688 break 2;
689 }
690 }
691
692 # Get the ParserOutput actually *displayed* here.
693 # Note that $this->mParserOutput is the *current* version output.
694 $pOutput = ( $outputDone instanceof ParserOutput )
695 ? $outputDone // object fetched by hook
696 : $this->mParserOutput;
697
698 # Adjust title for main page & pages with displaytitle
699 if ( $pOutput ) {
700 $this->adjustDisplayTitle( $pOutput );
701 }
702
703 # For the main page, overwrite the <title> element with the con-
704 # tents of 'pagetitle-view-mainpage' instead of the default (if
705 # that's not empty).
706 # This message always exists because it is in the i18n files
707 if ( $this->getTitle()->isMainPage() ) {
708 $msg = wfMessage( 'pagetitle-view-mainpage' )->inContentLanguage();
709 if ( !$msg->isDisabled() ) {
710 $wgOut->setHTMLTitle( $msg->title( $this->getTitle() )->text() );
711 }
712 }
713
714 # Check for any __NOINDEX__ tags on the page using $pOutput
715 $policy = $this->getRobotPolicy( 'view', $pOutput );
716 $wgOut->setIndexPolicy( $policy['index'] );
717 $wgOut->setFollowPolicy( $policy['follow'] );
718
719 $this->showViewFooter();
720 $this->mPage->doViewUpdates( $wgUser );
721
722 wfProfileOut( __METHOD__ );
723 }
724
725 /**
726 * Adjust title for pages with displaytitle, -{T|}- or language conversion
727 * @param $pOutput ParserOutput
728 */
729 public function adjustDisplayTitle( ParserOutput $pOutput ) {
730 global $wgOut;
731 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
732 $titleText = $pOutput->getTitleText();
733 if ( strval( $titleText ) !== '' ) {
734 $wgOut->setPageTitle( $titleText );
735 }
736 }
737
738 /**
739 * Show a diff page according to current request variables. For use within
740 * Article::view() only, other callers should use the DifferenceEngine class.
741 */
742 public function showDiffPage() {
743 global $wgRequest, $wgUser;
744
745 $diff = $wgRequest->getVal( 'diff' );
746 $rcid = $wgRequest->getVal( 'rcid' );
747 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
748 $purge = $wgRequest->getVal( 'action' ) == 'purge';
749 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
750 $oldid = $this->getOldID();
751
752 $contentHandler = ContentHandler::getForTitle( $this->getTitle() );
753 $de = $contentHandler->createDifferenceEngine( $this->getContext(), $oldid, $diff, $rcid, $purge, $unhide );
754
755 // DifferenceEngine directly fetched the revision:
756 $this->mRevIdFetched = $de->mNewid;
757 $de->showDiffPage( $diffOnly );
758
759 if ( $diff == 0 || $diff == $this->mPage->getLatest() ) {
760 # Run view updates for current revision only
761 $this->mPage->doViewUpdates( $wgUser );
762 }
763 }
764
765 /**
766 * Show a page view for a page formatted as CSS or JavaScript. To be called by
767 * Article::view() only.
768 *
769 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
770 * page views.
771 */
772 protected function showCssOrJsPage( $showCacheHint = true ) {
773 global $wgOut;
774
775 if ( $showCacheHint ) {
776 $dir = $this->getContext()->getLanguage()->getDir();
777 $lang = $this->getContext()->getLanguage()->getCode();
778
779 $wgOut->wrapWikiMsg( "<div id='mw-clearyourcache' lang='$lang' dir='$dir' class='mw-content-$dir'>\n$1\n</div>",
780 'clearyourcache' );
781 }
782
783 // Give hooks a chance to customise the output
784 if ( !Hooks::isRegistered('ShowRawCssJs') || wfRunHooks( 'ShowRawCssJs', array( $this->fetchContent(), $this->getTitle(), $wgOut ) ) ) { #FIXME: fetchContent() is deprecated #FIXME: hook is deprecated
785 $po = $this->mContentObject->getParserOutput( $this->getContext() );
786 $wgOut->addHTML( $po->getText() );
787 }
788 }
789
790 /**
791 * Get the robot policy to be used for the current view
792 * @param $action String the action= GET parameter
793 * @param $pOutput ParserOutput
794 * @return Array the policy that should be set
795 * TODO: actions other than 'view'
796 */
797 public function getRobotPolicy( $action, $pOutput ) {
798 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
799 global $wgDefaultRobotPolicy, $wgRequest;
800
801 $ns = $this->getTitle()->getNamespace();
802
803 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
804 # Don't index user and user talk pages for blocked users (bug 11443)
805 if ( !$this->getTitle()->isSubpage() ) {
806 if ( Block::newFromTarget( null, $this->getTitle()->getText() ) instanceof Block ) {
807 return array(
808 'index' => 'noindex',
809 'follow' => 'nofollow'
810 );
811 }
812 }
813 }
814
815 if ( $this->mPage->getID() === 0 || $this->getOldID() ) {
816 # Non-articles (special pages etc), and old revisions
817 return array(
818 'index' => 'noindex',
819 'follow' => 'nofollow'
820 );
821 } elseif ( $wgOut->isPrintable() ) {
822 # Discourage indexing of printable versions, but encourage following
823 return array(
824 'index' => 'noindex',
825 'follow' => 'follow'
826 );
827 } elseif ( $wgRequest->getInt( 'curid' ) ) {
828 # For ?curid=x urls, disallow indexing
829 return array(
830 'index' => 'noindex',
831 'follow' => 'follow'
832 );
833 }
834
835 # Otherwise, construct the policy based on the various config variables.
836 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
837
838 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
839 # Honour customised robot policies for this namespace
840 $policy = array_merge(
841 $policy,
842 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] )
843 );
844 }
845 if ( $this->getTitle()->canUseNoindex() && is_object( $pOutput ) && $pOutput->getIndexPolicy() ) {
846 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
847 # a final sanity check that we have really got the parser output.
848 $policy = array_merge(
849 $policy,
850 array( 'index' => $pOutput->getIndexPolicy() )
851 );
852 }
853
854 if ( isset( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] ) ) {
855 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
856 $policy = array_merge(
857 $policy,
858 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->getTitle()->getPrefixedText()] )
859 );
860 }
861
862 return $policy;
863 }
864
865 /**
866 * Converts a String robot policy into an associative array, to allow
867 * merging of several policies using array_merge().
868 * @param $policy Mixed, returns empty array on null/false/'', transparent
869 * to already-converted arrays, converts String.
870 * @return Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
871 */
872 public static function formatRobotPolicy( $policy ) {
873 if ( is_array( $policy ) ) {
874 return $policy;
875 } elseif ( !$policy ) {
876 return array();
877 }
878
879 $policy = explode( ',', $policy );
880 $policy = array_map( 'trim', $policy );
881
882 $arr = array();
883 foreach ( $policy as $var ) {
884 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
885 $arr['index'] = $var;
886 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
887 $arr['follow'] = $var;
888 }
889 }
890
891 return $arr;
892 }
893
894 /**
895 * If this request is a redirect view, send "redirected from" subtitle to
896 * $wgOut. Returns true if the header was needed, false if this is not a
897 * redirect view. Handles both local and remote redirects.
898 *
899 * @return boolean
900 */
901 public function showRedirectedFromHeader() {
902 global $wgOut, $wgRequest, $wgRedirectSources;
903
904 $rdfrom = $wgRequest->getVal( 'rdfrom' );
905
906 if ( isset( $this->mRedirectedFrom ) ) {
907 // This is an internally redirected page view.
908 // We'll need a backlink to the source page for navigation.
909 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
910 $redir = Linker::linkKnown(
911 $this->mRedirectedFrom,
912 null,
913 array(),
914 array( 'redirect' => 'no' )
915 );
916
917 $wgOut->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
918
919 // Set the fragment if one was specified in the redirect
920 if ( strval( $this->getTitle()->getFragment() ) != '' ) {
921 $fragment = Xml::escapeJsString( $this->getTitle()->getFragmentForURL() );
922 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
923 }
924
925 // Add a <link rel="canonical"> tag
926 $wgOut->addLink( array( 'rel' => 'canonical',
927 'href' => $this->getTitle()->getLocalURL() )
928 );
929
930 // Tell $wgOut the user arrived at this article through a redirect
931 $wgOut->setRedirectedFrom( $this->mRedirectedFrom );
932
933 return true;
934 }
935 } elseif ( $rdfrom ) {
936 // This is an externally redirected view, from some other wiki.
937 // If it was reported from a trusted site, supply a backlink.
938 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
939 $redir = Linker::makeExternalLink( $rdfrom, $rdfrom );
940 $wgOut->addSubtitle( wfMessage( 'redirectedfrom' )->rawParams( $redir ) );
941
942 return true;
943 }
944 }
945
946 return false;
947 }
948
949 /**
950 * Show a header specific to the namespace currently being viewed, like
951 * [[MediaWiki:Talkpagetext]]. For Article::view().
952 */
953 public function showNamespaceHeader() {
954 global $wgOut;
955
956 if ( $this->getTitle()->isTalkPage() ) {
957 if ( !wfMessage( 'talkpageheader' )->isDisabled() ) {
958 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>", array( 'talkpageheader' ) );
959 }
960 }
961 }
962
963 /**
964 * Show the footer section of an ordinary page view
965 */
966 public function showViewFooter() {
967 global $wgOut;
968
969 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
970 if ( $this->getTitle()->getNamespace() == NS_USER_TALK && IP::isValid( $this->getTitle()->getText() ) ) {
971 $wgOut->addWikiMsg( 'anontalkpagetext' );
972 }
973
974 # If we have been passed an &rcid= parameter, we want to give the user a
975 # chance to mark this new article as patrolled.
976 $this->showPatrolFooter();
977
978 wfRunHooks( 'ArticleViewFooter', array( $this ) );
979
980 }
981
982 /**
983 * If patrol is possible, output a patrol UI box. This is called from the
984 * footer section of ordinary page views. If patrol is not possible or not
985 * desired, does nothing.
986 */
987 public function showPatrolFooter() {
988 global $wgOut, $wgRequest, $wgUser;
989
990 $rcid = $wgRequest->getVal( 'rcid' );
991
992 if ( !$rcid || !$this->getTitle()->quickUserCan( 'patrol' ) ) {
993 return;
994 }
995
996 $token = $wgUser->getEditToken( $rcid );
997 $wgOut->preventClickjacking();
998
999 $wgOut->addHTML(
1000 "<div class='patrollink'>" .
1001 wfMsgHtml(
1002 'markaspatrolledlink',
1003 Linker::link(
1004 $this->getTitle(),
1005 wfMsgHtml( 'markaspatrolledtext' ),
1006 array(),
1007 array(
1008 'action' => 'markpatrolled',
1009 'rcid' => $rcid,
1010 'token' => $token,
1011 ),
1012 array( 'known', 'noclasses' )
1013 )
1014 ) .
1015 '</div>'
1016 );
1017 }
1018
1019 /**
1020 * Show the error text for a missing article. For articles in the MediaWiki
1021 * namespace, show the default message text. To be called from Article::view().
1022 */
1023 public function showMissingArticle() {
1024 global $wgOut, $wgRequest, $wgUser, $wgSend404Code;
1025
1026 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1027 if ( $this->getTitle()->getNamespace() == NS_USER || $this->getTitle()->getNamespace() == NS_USER_TALK ) {
1028 $parts = explode( '/', $this->getTitle()->getText() );
1029 $rootPart = $parts[0];
1030 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1031 $ip = User::isIP( $rootPart );
1032
1033 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1034 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>",
1035 array( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) ) );
1036 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1037 LogEventsList::showLogExtract(
1038 $wgOut,
1039 'block',
1040 $user->getUserPage()->getPrefixedText(),
1041 '',
1042 array(
1043 'lim' => 1,
1044 'showIfEmpty' => false,
1045 'msgKey' => array(
1046 'blocked-notice-logextract',
1047 $user->getName() # Support GENDER in notice
1048 )
1049 )
1050 );
1051 }
1052 }
1053
1054 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1055
1056 # Show delete and move logs
1057 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->getTitle()->getPrefixedText(), '',
1058 array( 'lim' => 10,
1059 'conds' => array( "log_action != 'revision'" ),
1060 'showIfEmpty' => false,
1061 'msgKey' => array( 'moveddeleted-notice' ) )
1062 );
1063
1064 if ( !$this->mPage->hasViewableContent() && $wgSend404Code ) {
1065 // If there's no backing content, send a 404 Not Found
1066 // for better machine handling of broken links.
1067 $wgRequest->response()->header( "HTTP/1.1 404 Not Found" );
1068 }
1069
1070 $hookResult = wfRunHooks( 'BeforeDisplayNoArticleText', array( $this ) );
1071
1072 if ( ! $hookResult ) {
1073 return;
1074 }
1075
1076 # Show error message
1077 $oldid = $this->getOldID();
1078 if ( $oldid ) {
1079 $text = wfMsgNoTrans( 'missing-article',
1080 $this->getTitle()->getPrefixedText(),
1081 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1082 } elseif ( $this->getTitle()->getNamespace() === NS_MEDIAWIKI ) {
1083 // Use the default message text
1084 $text = $this->getTitle()->getDefaultMessageText();
1085 } else {
1086 $createErrors = $this->getTitle()->getUserPermissionsErrors( 'create', $wgUser );
1087 $editErrors = $this->getTitle()->getUserPermissionsErrors( 'edit', $wgUser );
1088 $errors = array_merge( $createErrors, $editErrors );
1089
1090 if ( !count( $errors ) ) {
1091 $text = wfMsgNoTrans( 'noarticletext' );
1092 } else {
1093 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1094 }
1095 }
1096 $text = "<div class='noarticletext'>\n$text\n</div>";
1097
1098 $wgOut->addWikiText( $text );
1099 }
1100
1101 /**
1102 * If the revision requested for view is deleted, check permissions.
1103 * Send either an error message or a warning header to $wgOut.
1104 *
1105 * @return boolean true if the view is allowed, false if not.
1106 */
1107 public function showDeletedRevisionHeader() {
1108 global $wgOut, $wgRequest;
1109
1110 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1111 // Not deleted
1112 return true;
1113 }
1114
1115 // If the user is not allowed to see it...
1116 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1117 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1118 'rev-deleted-text-permission' );
1119
1120 return false;
1121 // If the user needs to confirm that they want to see it...
1122 } elseif ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1123 # Give explanation and add a link to view the revision...
1124 $oldid = intval( $this->getOldID() );
1125 $link = $this->getTitle()->getFullUrl( "oldid={$oldid}&unhide=1" );
1126 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1127 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1128 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
1129 array( $msg, $link ) );
1130
1131 return false;
1132 // We are allowed to see...
1133 } else {
1134 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1135 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1136 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", $msg );
1137
1138 return true;
1139 }
1140 }
1141
1142 /**
1143 * Generate the navigation links when browsing through an article revisions
1144 * It shows the information as:
1145 * Revision as of \<date\>; view current revision
1146 * \<- Previous version | Next Version -\>
1147 *
1148 * @param $oldid String: revision ID of this article revision
1149 */
1150 public function setOldSubtitle( $oldid = 0 ) {
1151 global $wgLang, $wgOut, $wgUser, $wgRequest;
1152
1153 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
1154 return;
1155 }
1156
1157 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
1158
1159 # Cascade unhide param in links for easy deletion browsing
1160 $extraParams = array();
1161 if ( $unhide ) {
1162 $extraParams['unhide'] = 1;
1163 }
1164
1165 if ( $this->mRevision && $this->mRevision->getId() === $oldid ) {
1166 $revision = $this->mRevision;
1167 } else {
1168 $revision = Revision::newFromId( $oldid );
1169 }
1170
1171 $timestamp = $revision->getTimestamp();
1172
1173 $current = ( $oldid == $this->mPage->getLatest() );
1174 $td = $wgLang->timeanddate( $timestamp, true );
1175 $tddate = $wgLang->date( $timestamp, true );
1176 $tdtime = $wgLang->time( $timestamp, true );
1177
1178 # Show user links if allowed to see them. If hidden, then show them only if requested...
1179 $userlinks = Linker::revUserTools( $revision, !$unhide );
1180
1181 $infomsg = $current && !wfMessage( 'revision-info-current' )->isDisabled()
1182 ? 'revision-info-current'
1183 : 'revision-info';
1184
1185 $wgOut->addSubtitle( "<div id=\"mw-{$infomsg}\">" . wfMessage( $infomsg,
1186 $td )->rawParams( $userlinks )->params( $revision->getID(), $tddate,
1187 $tdtime, $revision->getUser() )->parse() . "</div>" );
1188
1189 $lnk = $current
1190 ? wfMsgHtml( 'currentrevisionlink' )
1191 : Linker::link(
1192 $this->getTitle(),
1193 wfMsgHtml( 'currentrevisionlink' ),
1194 array(),
1195 $extraParams,
1196 array( 'known', 'noclasses' )
1197 );
1198 $curdiff = $current
1199 ? wfMsgHtml( 'diff' )
1200 : Linker::link(
1201 $this->getTitle(),
1202 wfMsgHtml( 'diff' ),
1203 array(),
1204 array(
1205 'diff' => 'cur',
1206 'oldid' => $oldid
1207 ) + $extraParams,
1208 array( 'known', 'noclasses' )
1209 );
1210 $prev = $this->getTitle()->getPreviousRevisionID( $oldid ) ;
1211 $prevlink = $prev
1212 ? Linker::link(
1213 $this->getTitle(),
1214 wfMsgHtml( 'previousrevision' ),
1215 array(),
1216 array(
1217 'direction' => 'prev',
1218 'oldid' => $oldid
1219 ) + $extraParams,
1220 array( 'known', 'noclasses' )
1221 )
1222 : wfMsgHtml( 'previousrevision' );
1223 $prevdiff = $prev
1224 ? Linker::link(
1225 $this->getTitle(),
1226 wfMsgHtml( 'diff' ),
1227 array(),
1228 array(
1229 'diff' => 'prev',
1230 'oldid' => $oldid
1231 ) + $extraParams,
1232 array( 'known', 'noclasses' )
1233 )
1234 : wfMsgHtml( 'diff' );
1235 $nextlink = $current
1236 ? wfMsgHtml( 'nextrevision' )
1237 : Linker::link(
1238 $this->getTitle(),
1239 wfMsgHtml( 'nextrevision' ),
1240 array(),
1241 array(
1242 'direction' => 'next',
1243 'oldid' => $oldid
1244 ) + $extraParams,
1245 array( 'known', 'noclasses' )
1246 );
1247 $nextdiff = $current
1248 ? wfMsgHtml( 'diff' )
1249 : Linker::link(
1250 $this->getTitle(),
1251 wfMsgHtml( 'diff' ),
1252 array(),
1253 array(
1254 'diff' => 'next',
1255 'oldid' => $oldid
1256 ) + $extraParams,
1257 array( 'known', 'noclasses' )
1258 );
1259
1260 $cdel = Linker::getRevDeleteLink( $wgUser, $revision, $this->getTitle() );
1261 if ( $cdel !== '' ) {
1262 $cdel .= ' ';
1263 }
1264
1265 $wgOut->addSubtitle( "<div id=\"mw-revision-nav\">" . $cdel .
1266 wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
1267 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>" );
1268 }
1269
1270 /**
1271 * View redirect
1272 *
1273 * @param $target Title|Array of destination(s) to redirect
1274 * @param $appendSubtitle Boolean [optional]
1275 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1276 * @return string containing HMTL with redirect link
1277 */
1278 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1279 global $wgOut, $wgStylePath;
1280
1281 if ( !is_array( $target ) ) {
1282 $target = array( $target );
1283 }
1284
1285 $lang = $this->getTitle()->getPageLanguage();
1286 $imageDir = $lang->getDir();
1287
1288 if ( $appendSubtitle ) {
1289 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1290 }
1291
1292 // the loop prepends the arrow image before the link, so the first case needs to be outside
1293
1294 /**
1295 * @var $title Title
1296 */
1297 $title = array_shift( $target );
1298
1299 if ( $forceKnown ) {
1300 $link = Linker::linkKnown( $title, htmlspecialchars( $title->getFullText() ) );
1301 } else {
1302 $link = Linker::link( $title, htmlspecialchars( $title->getFullText() ) );
1303 }
1304
1305 $nextRedirect = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1306 $alt = $lang->isRTL() ? '←' : '→';
1307 // Automatically append redirect=no to each link, since most of them are redirect pages themselves.
1308 foreach ( $target as $rt ) {
1309 $link .= Html::element( 'img', array( 'src' => $nextRedirect, 'alt' => $alt ) );
1310 if ( $forceKnown ) {
1311 $link .= Linker::linkKnown( $rt, htmlspecialchars( $rt->getFullText(), array(), array( 'redirect' => 'no' ) ) );
1312 } else {
1313 $link .= Linker::link( $rt, htmlspecialchars( $rt->getFullText() ), array(), array( 'redirect' => 'no' ) );
1314 }
1315 }
1316
1317 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1318 return '<div class="redirectMsg">' .
1319 Html::element( 'img', array( 'src' => $imageUrl, 'alt' => '#REDIRECT' ) ) .
1320 '<span class="redirectText">' . $link . '</span></div>';
1321 }
1322
1323 /**
1324 * Handle action=render
1325 */
1326 public function render() {
1327 global $wgOut;
1328
1329 $wgOut->setArticleBodyOnly( true );
1330 $this->view();
1331 }
1332
1333 /**
1334 * action=protect handler
1335 */
1336 public function protect() {
1337 $form = new ProtectionForm( $this );
1338 $form->execute();
1339 }
1340
1341 /**
1342 * action=unprotect handler (alias)
1343 */
1344 public function unprotect() {
1345 $this->protect();
1346 }
1347
1348 /**
1349 * UI entry point for page deletion
1350 */
1351 public function delete() {
1352 global $wgOut, $wgRequest, $wgLang;
1353
1354 # This code desperately needs to be totally rewritten
1355
1356 $title = $this->getTitle();
1357 $user = $this->getContext()->getUser();
1358
1359 # Check permissions
1360 $permission_errors = $title->getUserPermissionsErrors( 'delete', $user );
1361 if ( count( $permission_errors ) ) {
1362 throw new PermissionsError( 'delete', $permission_errors );
1363 }
1364
1365 # Read-only check...
1366 if ( wfReadOnly() ) {
1367 throw new ReadOnlyError;
1368 }
1369
1370 # Better double-check that it hasn't been deleted yet!
1371 $dbw = wfGetDB( DB_MASTER );
1372 $conds = $title->pageCond();
1373 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
1374 if ( $latest === false ) {
1375 $wgOut->setPageTitle( wfMessage( 'cannotdelete-title', $title->getPrefixedText() ) );
1376 $wgOut->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1377 array( 'cannotdelete', wfEscapeWikiText( $title->getPrefixedText() ) )
1378 );
1379 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1380 LogEventsList::showLogExtract(
1381 $wgOut,
1382 'delete',
1383 $title->getPrefixedText()
1384 );
1385
1386 return;
1387 }
1388
1389 $deleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
1390 $deleteReason = $wgRequest->getText( 'wpReason' );
1391
1392 if ( $deleteReasonList == 'other' ) {
1393 $reason = $deleteReason;
1394 } elseif ( $deleteReason != '' ) {
1395 // Entry from drop down menu + additional comment
1396 $reason = $deleteReasonList . wfMsgForContent( 'colon-separator' ) . $deleteReason;
1397 } else {
1398 $reason = $deleteReasonList;
1399 }
1400
1401 if ( $wgRequest->wasPosted() && $user->matchEditToken( $wgRequest->getVal( 'wpEditToken' ),
1402 array( 'delete', $this->getTitle()->getPrefixedText() ) ) )
1403 {
1404 # Flag to hide all contents of the archived revisions
1405 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $user->isAllowed( 'suppressrevision' );
1406
1407 $this->doDelete( $reason, $suppress );
1408
1409 if ( $wgRequest->getCheck( 'wpWatch' ) && $user->isLoggedIn() ) {
1410 $this->doWatch();
1411 } elseif ( $title->userIsWatching() ) {
1412 $this->doUnwatch();
1413 }
1414
1415 return;
1416 }
1417
1418 // Generate deletion reason
1419 $hasHistory = false;
1420 if ( !$reason ) {
1421 try {
1422 $reason = $this->generateReason( $hasHistory );
1423 } catch (MWException $e) {
1424 # if a page is horribly broken, we still want to be able to delete it. so be lenient about errors here.
1425 wfDebug("Error while building auto delete summary: $e");
1426 $reason = '';
1427 }
1428 }
1429
1430 // If the page has a history, insert a warning
1431 if ( $hasHistory ) {
1432 $revisions = $this->mTitle->estimateRevisionCount();
1433 // @todo FIXME: i18n issue/patchwork message
1434 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
1435 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
1436 wfMsgHtml( 'word-separator' ) . Linker::link( $title,
1437 wfMsgHtml( 'history' ),
1438 array( 'rel' => 'archives' ),
1439 array( 'action' => 'history' ) ) .
1440 '</strong>'
1441 );
1442
1443 if ( $this->mTitle->isBigDeletion() ) {
1444 global $wgDeleteRevisionsLimit;
1445 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n",
1446 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
1447 }
1448 }
1449
1450 return $this->confirmDelete( $reason );
1451 }
1452
1453 /**
1454 * Output deletion confirmation dialog
1455 * @todo FIXME: Move to another file?
1456 * @param $reason String: prefilled reason
1457 */
1458 public function confirmDelete( $reason ) {
1459 global $wgOut;
1460
1461 wfDebug( "Article::confirmDelete\n" );
1462
1463 $wgOut->setPageTitle( wfMessage( 'delete-confirm', $this->getTitle()->getPrefixedText() ) );
1464 $wgOut->addBacklinkSubtitle( $this->getTitle() );
1465 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1466 $wgOut->addWikiMsg( 'confirmdeletetext' );
1467
1468 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
1469
1470 $user = $this->getContext()->getUser();
1471
1472 if ( $user->isAllowed( 'suppressrevision' ) ) {
1473 $suppress = "<tr id=\"wpDeleteSuppressRow\">
1474 <td></td>
1475 <td class='mw-input'><strong>" .
1476 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
1477 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
1478 "</strong></td>
1479 </tr>";
1480 } else {
1481 $suppress = '';
1482 }
1483 $checkWatch = $user->getBoolOption( 'watchdeletion' ) || $this->getTitle()->userIsWatching();
1484
1485 $form = Xml::openElement( 'form', array( 'method' => 'post',
1486 'action' => $this->getTitle()->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
1487 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
1488 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
1489 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
1490 "<tr id=\"wpDeleteReasonListRow\">
1491 <td class='mw-label'>" .
1492 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
1493 "</td>
1494 <td class='mw-input'>" .
1495 Xml::listDropDown( 'wpDeleteReasonList',
1496 wfMsgForContent( 'deletereason-dropdown' ),
1497 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
1498 "</td>
1499 </tr>
1500 <tr id=\"wpDeleteReasonRow\">
1501 <td class='mw-label'>" .
1502 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
1503 "</td>
1504 <td class='mw-input'>" .
1505 Html::input( 'wpReason', $reason, 'text', array(
1506 'size' => '60',
1507 'maxlength' => '255',
1508 'tabindex' => '2',
1509 'id' => 'wpReason',
1510 'autofocus'
1511 ) ) .
1512 "</td>
1513 </tr>";
1514
1515 # Disallow watching if user is not logged in
1516 if ( $user->isLoggedIn() ) {
1517 $form .= "
1518 <tr>
1519 <td></td>
1520 <td class='mw-input'>" .
1521 Xml::checkLabel( wfMsg( 'watchthis' ),
1522 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
1523 "</td>
1524 </tr>";
1525 }
1526
1527 $form .= "
1528 $suppress
1529 <tr>
1530 <td></td>
1531 <td class='mw-submit'>" .
1532 Xml::submitButton( wfMsg( 'deletepage' ),
1533 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
1534 "</td>
1535 </tr>" .
1536 Xml::closeElement( 'table' ) .
1537 Xml::closeElement( 'fieldset' ) .
1538 Html::hidden( 'wpEditToken', $user->getEditToken( array( 'delete', $this->getTitle()->getPrefixedText() ) ) ) .
1539 Xml::closeElement( 'form' );
1540
1541 if ( $user->isAllowed( 'editinterface' ) ) {
1542 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
1543 $link = Linker::link(
1544 $title,
1545 wfMsgHtml( 'delete-edit-reasonlist' ),
1546 array(),
1547 array( 'action' => 'edit' )
1548 );
1549 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
1550 }
1551
1552 $wgOut->addHTML( $form );
1553 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1554 LogEventsList::showLogExtract( $wgOut, 'delete',
1555 $this->getTitle()->getPrefixedText()
1556 );
1557 }
1558
1559 /**
1560 * Perform a deletion and output success or failure messages
1561 * @param $reason
1562 * @param $suppress bool
1563 */
1564 public function doDelete( $reason, $suppress = false ) {
1565 global $wgOut;
1566
1567 $error = '';
1568 if ( $this->mPage->doDeleteArticle( $reason, $suppress, 0, true, $error ) ) {
1569 $deleted = $this->getTitle()->getPrefixedText();
1570
1571 $wgOut->setPageTitle( wfMessage( 'actioncomplete' ) );
1572 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1573
1574 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
1575
1576 $wgOut->addWikiMsg( 'deletedtext', wfEscapeWikiText( $deleted ), $loglink );
1577 $wgOut->returnToMain( false );
1578 } else {
1579 $wgOut->setPageTitle( wfMessage( 'cannotdelete-title', $this->getTitle()->getPrefixedText() ) );
1580 if ( $error == '' ) {
1581 $wgOut->wrapWikiMsg( "<div class=\"error mw-error-cannotdelete\">\n$1\n</div>",
1582 array( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) )
1583 );
1584 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
1585
1586 LogEventsList::showLogExtract(
1587 $wgOut,
1588 'delete',
1589 $this->getTitle()->getPrefixedText()
1590 );
1591 } else {
1592 $wgOut->addHTML( $error );
1593 }
1594 }
1595 }
1596
1597 /* Caching functions */
1598
1599 /**
1600 * checkLastModified returns true if it has taken care of all
1601 * output to the client that is necessary for this request.
1602 * (that is, it has sent a cached version of the page)
1603 *
1604 * @return boolean true if cached version send, false otherwise
1605 */
1606 protected function tryFileCache() {
1607 static $called = false;
1608
1609 if ( $called ) {
1610 wfDebug( "Article::tryFileCache(): called twice!?\n" );
1611 return false;
1612 }
1613
1614 $called = true;
1615 if ( $this->isFileCacheable() ) {
1616 $cache = HTMLFileCache::newFromTitle( $this->getTitle(), 'view' );
1617 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1618 wfDebug( "Article::tryFileCache(): about to load file\n" );
1619 $cache->loadFromFileCache( $this->getContext() );
1620 return true;
1621 } else {
1622 wfDebug( "Article::tryFileCache(): starting buffer\n" );
1623 ob_start( array( &$cache, 'saveToFileCache' ) );
1624 }
1625 } else {
1626 wfDebug( "Article::tryFileCache(): not cacheable\n" );
1627 }
1628
1629 return false;
1630 }
1631
1632 /**
1633 * Check if the page can be cached
1634 * @return bool
1635 */
1636 public function isFileCacheable() {
1637 $cacheable = false;
1638
1639 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
1640 $cacheable = $this->mPage->getID()
1641 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
1642 // Extension may have reason to disable file caching on some pages.
1643 if ( $cacheable ) {
1644 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
1645 }
1646 }
1647
1648 return $cacheable;
1649 }
1650
1651 /**#@-*/
1652
1653 /**
1654 * Lightweight method to get the parser output for a page, checking the parser cache
1655 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
1656 * consider, so it's not appropriate to use there.
1657 *
1658 * @since 1.16 (r52326) for LiquidThreads
1659 *
1660 * @param $oldid mixed integer Revision ID or null
1661 * @param $user User The relevant user
1662 * @return ParserOutput or false if the given revsion ID is not found
1663 */
1664 public function getParserOutput( $oldid = null, User $user = null ) {
1665 global $wgUser;
1666
1667 $user = is_null( $user ) ? $wgUser : $user;
1668 $parserOptions = $this->mPage->makeParserOptions( $user );
1669
1670 return $this->mPage->getParserOutput( $parserOptions, $oldid );
1671 }
1672
1673 /**
1674 * Get parser options suitable for rendering the primary article wikitext
1675 * @return ParserOptions
1676 */
1677 public function getParserOptions() {
1678 global $wgUser;
1679 if ( !$this->mParserOptions ) {
1680 $this->mParserOptions = $this->mPage->makeParserOptions( $wgUser );
1681 }
1682 // Clone to allow modifications of the return value without affecting cache
1683 return clone $this->mParserOptions;
1684 }
1685
1686 /**
1687 * Sets the context this Article is executed in
1688 *
1689 * @param $context IContextSource
1690 * @since 1.18
1691 */
1692 public function setContext( $context ) {
1693 $this->mContext = $context;
1694 }
1695
1696 /**
1697 * Gets the context this Article is executed in
1698 *
1699 * @return IContextSource
1700 * @since 1.18
1701 */
1702 public function getContext() {
1703 if ( $this->mContext instanceof IContextSource ) {
1704 return $this->mContext;
1705 } else {
1706 wfDebug( __METHOD__ . " called and \$mContext is null. Return RequestContext::getMain(); for sanity\n" );
1707 return RequestContext::getMain();
1708 }
1709 }
1710
1711 /**
1712 * Info about this page
1713 * @deprecated since 1.19
1714 */
1715 public function info() {
1716 wfDeprecated( __METHOD__, '1.19' );
1717 Action::factory( 'info', $this )->show();
1718 }
1719
1720 /**
1721 * Mark this particular edit/page as patrolled
1722 * @deprecated since 1.18
1723 */
1724 public function markpatrolled() {
1725 wfDeprecated( __METHOD__, '1.18' );
1726 Action::factory( 'markpatrolled', $this )->show();
1727 }
1728
1729 /**
1730 * Handle action=purge
1731 * @deprecated since 1.19
1732 */
1733 public function purge() {
1734 return Action::factory( 'purge', $this )->show();
1735 }
1736
1737 /**
1738 * Handle action=revert
1739 * @deprecated since 1.19
1740 */
1741 public function revert() {
1742 wfDeprecated( __METHOD__, '1.19' );
1743 Action::factory( 'revert', $this )->show();
1744 }
1745
1746 /**
1747 * Handle action=rollback
1748 * @deprecated since 1.19
1749 */
1750 public function rollback() {
1751 wfDeprecated( __METHOD__, '1.19' );
1752 Action::factory( 'rollback', $this )->show();
1753 }
1754
1755 /**
1756 * User-interface handler for the "watch" action.
1757 * Requires Request to pass a token as of 1.18.
1758 * @deprecated since 1.18
1759 */
1760 public function watch() {
1761 wfDeprecated( __METHOD__, '1.18' );
1762 Action::factory( 'watch', $this )->show();
1763 }
1764
1765 /**
1766 * Add this page to $wgUser's watchlist
1767 *
1768 * This is safe to be called multiple times
1769 *
1770 * @return bool true on successful watch operation
1771 * @deprecated since 1.18
1772 */
1773 public function doWatch() {
1774 global $wgUser;
1775 wfDeprecated( __METHOD__, '1.18' );
1776 return WatchAction::doWatch( $this->getTitle(), $wgUser );
1777 }
1778
1779 /**
1780 * User interface handler for the "unwatch" action.
1781 * Requires Request to pass a token as of 1.18.
1782 * @deprecated since 1.18
1783 */
1784 public function unwatch() {
1785 wfDeprecated( __METHOD__, '1.18' );
1786 Action::factory( 'unwatch', $this )->show();
1787 }
1788
1789 /**
1790 * Stop watching a page
1791 * @return bool true on successful unwatch
1792 * @deprecated since 1.18
1793 */
1794 public function doUnwatch() {
1795 global $wgUser;
1796 wfDeprecated( __METHOD__, '1.18' );
1797 return WatchAction::doUnwatch( $this->getTitle(), $wgUser );
1798 }
1799
1800 /**
1801 * Output a redirect back to the article.
1802 * This is typically used after an edit.
1803 *
1804 * @deprecated in 1.18; call $wgOut->redirect() directly
1805 * @param $noRedir Boolean: add redirect=no
1806 * @param $sectionAnchor String: section to redirect to, including "#"
1807 * @param $extraQuery String: extra query params
1808 */
1809 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
1810 wfDeprecated( __METHOD__, '1.18' );
1811 global $wgOut;
1812
1813 if ( $noRedir ) {
1814 $query = 'redirect=no';
1815 if ( $extraQuery )
1816 $query .= "&$extraQuery";
1817 } else {
1818 $query = $extraQuery;
1819 }
1820
1821 $wgOut->redirect( $this->getTitle()->getFullURL( $query ) . $sectionAnchor );
1822 }
1823
1824 /**
1825 * Use PHP's magic __get handler to handle accessing of
1826 * raw WikiPage fields for backwards compatibility.
1827 *
1828 * @param $fname String Field name
1829 */
1830 public function __get( $fname ) {
1831 if ( property_exists( $this->mPage, $fname ) ) {
1832 #wfWarn( "Access to raw $fname field " . __CLASS__ );
1833 return $this->mPage->$fname;
1834 }
1835 trigger_error( 'Inaccessible property via __get(): ' . $fname, E_USER_NOTICE );
1836 }
1837
1838 /**
1839 * Use PHP's magic __set handler to handle setting of
1840 * raw WikiPage fields for backwards compatibility.
1841 *
1842 * @param $fname String Field name
1843 * @param $fvalue mixed New value
1844 */
1845 public function __set( $fname, $fvalue ) {
1846 if ( property_exists( $this->mPage, $fname ) ) {
1847 #wfWarn( "Access to raw $fname field of " . __CLASS__ );
1848 $this->mPage->$fname = $fvalue;
1849 // Note: extensions may want to toss on new fields
1850 } elseif ( !in_array( $fname, array( 'mContext', 'mPage' ) ) ) {
1851 $this->mPage->$fname = $fvalue;
1852 } else {
1853 trigger_error( 'Inaccessible property via __set(): ' . $fname, E_USER_NOTICE );
1854 }
1855 }
1856
1857 /**
1858 * Use PHP's magic __call handler to transform instance calls to
1859 * WikiPage functions for backwards compatibility.
1860 *
1861 * @param $fname String Name of called method
1862 * @param $args Array Arguments to the method
1863 * @return mixed
1864 */
1865 public function __call( $fname, $args ) {
1866 if ( is_callable( array( $this->mPage, $fname ) ) ) {
1867 #wfWarn( "Call to " . __CLASS__ . "::$fname; please use WikiPage instead" );
1868 return call_user_func_array( array( $this->mPage, $fname ), $args );
1869 }
1870 trigger_error( 'Inaccessible function via __call(): ' . $fname, E_USER_ERROR );
1871 }
1872
1873 // ****** B/C functions to work-around PHP silliness with __call and references ****** //
1874
1875 /**
1876 * @param $limit array
1877 * @param $expiry array
1878 * @param $cascade bool
1879 * @param $reason string
1880 * @param $user User
1881 * @return Status
1882 */
1883 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
1884 return $this->mPage->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user );
1885 }
1886
1887 /**
1888 * @param $limit array
1889 * @param $reason string
1890 * @param $cascade int
1891 * @param $expiry array
1892 * @return bool
1893 */
1894 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
1895 return $this->mPage->updateRestrictions( $limit, $reason, $cascade, $expiry );
1896 }
1897
1898 /**
1899 * @param $reason string
1900 * @param $suppress bool
1901 * @param $id int
1902 * @param $commit bool
1903 * @param $error string
1904 * @return bool
1905 */
1906 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true, &$error = '' ) {
1907 return $this->mPage->doDeleteArticle( $reason, $suppress, $id, $commit, $error );
1908 }
1909
1910 /**
1911 * @param $fromP
1912 * @param $summary
1913 * @param $token
1914 * @param $bot
1915 * @param $resultDetails
1916 * @param $user User
1917 * @return array
1918 */
1919 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails, User $user = null ) {
1920 global $wgUser;
1921 $user = is_null( $user ) ? $wgUser : $user;
1922 return $this->mPage->doRollback( $fromP, $summary, $token, $bot, $resultDetails, $user );
1923 }
1924
1925 /**
1926 * @param $fromP
1927 * @param $summary
1928 * @param $bot
1929 * @param $resultDetails
1930 * @param $guser User
1931 * @return array
1932 */
1933 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
1934 global $wgUser;
1935 $guser = is_null( $guser ) ? $wgUser : $guser;
1936 return $this->mPage->commitRollback( $fromP, $summary, $bot, $resultDetails, $guser );
1937 }
1938
1939 /**
1940 * @param $hasHistory bool
1941 * @return mixed
1942 */
1943 public function generateReason( &$hasHistory ) {
1944 $title = $this->mPage->getTitle();
1945 $handler = ContentHandler::getForTitle( $title );
1946 return $handler->getAutoDeleteReason( $title, $hasHistory );
1947 }
1948
1949 // ****** B/C functions for static methods ( __callStatic is PHP>=5.3 ) ****** //
1950
1951 /**
1952 * @return array
1953 */
1954 public static function selectFields() {
1955 return WikiPage::selectFields();
1956 }
1957
1958 /**
1959 * @param $title Title
1960 */
1961 public static function onArticleCreate( $title ) {
1962 WikiPage::onArticleCreate( $title );
1963 }
1964
1965 /**
1966 * @param $title Title
1967 */
1968 public static function onArticleDelete( $title ) {
1969 WikiPage::onArticleDelete( $title );
1970 }
1971
1972 /**
1973 * @param $title Title
1974 */
1975 public static function onArticleEdit( $title ) {
1976 WikiPage::onArticleEdit( $title );
1977 }
1978
1979 /**
1980 * @param $oldtext
1981 * @param $newtext
1982 * @param $flags
1983 * @return string
1984 * @deprecated since 1.WD, use ContentHandler::getAutosummary() instead
1985 */
1986 public static function getAutosummary( $oldtext, $newtext, $flags ) {
1987 return WikiPage::getAutosummary( $oldtext, $newtext, $flags );
1988 }
1989 // ******
1990 }